﻿using SuperiorCommon;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;

namespace Api.SuperiorShop.Controllers
{
    public class WeiXinController : ApiControllerBase
    {
        // GET: WeiXin
        [HttpGet]
        public HttpResponseMessage Recive()
        {
            if (!string.IsNullOrEmpty(HttpContext.Current.Request["signature"]) && !string.IsNullOrEmpty(HttpContext.Current.Request["timestamp"]) && !string.IsNullOrEmpty(HttpContext.Current.Request["nonce"]))
            {
                string signature = HttpContext.Current.Request["signature"].Trim();
                string timestamp = HttpContext.Current.Request["timestamp"].Trim();
                string nonce = HttpContext.Current.Request["nonce"].Trim();
                if (HttpContext.Current.Request.HttpMethod.ToLower() == "get" && !string.IsNullOrEmpty(HttpContext.Current.Request["echostr"]))
                {
                    string echostr = HttpContext.Current.Request["echostr"].Trim();
                    if (WeiXinHelper.VerifySignature(timestamp, nonce, signature))
                    {
                        return base.RetMessage(echostr);
                    }
                }
                if (HttpContext.Current.Request.HttpMethod.ToLower() == "post")
                {
                    if (!WeiXinHelper.VerifySignature(timestamp, nonce, signature))
                    {
                        LogManger.Instance.WriteLog("错误：微信信息验证失败，timestamp:" + timestamp + "nonce:" + nonce + "signature:" + signature);
                        return base.RetMessage("");
                    }
                    string sPostXml = "";
                    Stream s = HttpContext.Current.Request.InputStream;
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, (int)s.Length);
                    string sPostData = Encoding.UTF8.GetString(b);
                    string encrypt_type = "raw";
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request["encrypt_type"]) && HttpContext.Current.Request["encrypt_type"] == "aes" && !string.IsNullOrEmpty(HttpContext.Current.Request["msg_signature"]))
                    {
                        encrypt_type = "aes";
                        string msg_signature = HttpContext.Current.Request["msg_signature"].Trim();
                        //采用信息aes加密
                        string sMsg = "";  //解析之后的明文
                        int ret = WeiXinHelper.DecryptMsg(msg_signature, timestamp, nonce, sPostData, ref sMsg);
                        if (ret != 0)
                        {
                            LogManger.Instance.WriteLog("错误：微信解密失败，ret：" + ret + ";内容：" + sPostData);
                            return base.RetMessage("");
                        }
                        LogManger.Instance.WriteLog(sMsg);
                        sPostXml = sMsg;
                    }
                    else
                    {
                        sPostXml = sPostData;
                    }
                    XmlDocument doc = new XmlDocument();
                    try
                    {
                        doc.LoadXml(sPostXml);
                        XmlElement rootElement = doc.DocumentElement;
                        RequestXML requestXML = new RequestXML();
                        requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
                        requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
                        requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
                        requestXML.MsgType = rootElement.SelectSingleNode("MsgType").InnerText;
                        if (requestXML.MsgType == "text")//文本
                        {
                            requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
                        }
                        else if (requestXML.MsgType == "event")//事件
                        {
                            requestXML.EventType = rootElement.SelectSingleNode("Event").InnerText;
                            requestXML.Key = rootElement.SelectSingleNode("EventKey") == null ? "" : rootElement.SelectSingleNode("EventKey").InnerText;
                        }
                        if (rootElement.SelectSingleNode("MsgID") != null)
                        {
                            requestXML.MsgID = rootElement.SelectSingleNode("MsgID").InnerText;
                        }
                        if (rootElement.SelectSingleNode("Status") != null)
                        {
                            requestXML.Status = rootElement.SelectSingleNode("Status").InnerText;
                        }
                        //回复消息
                        ResponseMsg(requestXML, encrypt_type, timestamp, nonce);
                    }
                    catch (Exception ex)
                    {
                        LogManger.Instance.WriteLog("错误：加载微信XML异常，异常信息：" + ex.Message + "异常堆栈：" + ex.StackTrace);
                    }
                }
            }
            return base.RetMessage("");
        }

        /// <summary>
        /// 回复消息(微信信息返回)
        /// </summary>
        /// <param name="weixinXML"></param>
        private void ResponseMsg(RequestXML requestXML, string encrypt_type, string timestamp, string nonce)
        {
            string resxml = string.Empty;
            if (requestXML.MsgType == "text")
            {
                if (requestXML.Content == "签到")
                {

                }
            }
            if (requestXML.MsgType == "event")
            {
            }
        }
    }
}